<template>
	<view class="content">
		<textarea class="textareas" maxlength="-1" v-model="searchData.codes" :confirm-hold="true" confirm-type="return"
			placeholder="请输入柜号，多个编码之间以换行拼接，禁止输入特殊字符！最多30个设备号" placeholder-style="font-size:28rpx" :rows="6"
			@change.native="keyUp($event)" @input.native="keyInput($event)" @blur.native="keyBlur($event)"></textarea>
		<view class="search_btns">
			<button type="primary" size="mini" @click="doSearch">搜索</button>
		</view>
		<view class="tab">
			<uni-segmented-control :current="0" styleType="text" :values="['升级平台链接参数']">
			</uni-segmented-control>
		</view>
		<view class="param-content">
			<view class="param-one">
				<text>服务地址</text>
				<input v-model="operateForm.url" class="uni-input" placeholder="请输入服务地址" />
			</view>
			<view class="param-one">
				<text>端口</text>
				<input v-model="operateForm.port" class="uni-input" placeholder="请输入端口" />
			</view>
			<view class="param-one">
				<text>用户名</text>
				<input v-model="operateForm.username" class="uni-input" placeholder="请输入用户名" />
			</view>
			<view class="param-one">
				<text>密码</text>
				<input v-model="operateForm.password" @input="onPasswordInput('password')" class="uni-input" placeholder="请输入密码" />
			</view>
			<view class="param-one">
				<text>产品密钥</text>
				<input v-model="operateForm.productKey" @input="onPasswordInput('productKey')" class="uni-input" placeholder="请输入产品密钥" />
			</view>
			<view class="param-one">
				<text>设备名称</text>
				<input v-model="operateForm.deviceName" class="uni-input" placeholder="请输入设备名称" />
			</view>
			<view class="param-one">
				<text>设备密钥</text>
				<input v-model="operateForm.deviceSecret" @input="onPasswordInput('deviceSecret')" class="uni-input" placeholder="请输入设备密钥" />
			</view>
		</view>

		<view class="search_btns">
			<button type="primary" size="mini" @click="isSetting" v-if="permission('applet:batchconnection:setting')">批量设置</button>
		</view>
		<view class="table-title" v-if="nofoundList.length>0" style="color: red;">
			未搜索到的设备列表
		</view>
		<uni-list class="nofoundList" v-if="nofoundList.length>0">
			<uni-list-item title="编码">
				<template slot="footer">
					<text style="font-size: 24rpx;">复制</text>
				</template>
			</uni-list-item>
			<uni-list-item v-for="(item,index) in nofoundList" :key="index" :title="item">
				<template slot="footer">
					<text class="iconfont icon-copy" @click="isCopy(item)"></text>
				</template>
			</uni-list-item>
		</uni-list>
		<view class="table-title">
			<view class="head-title">柜列表 <span class="isAllow" v-if="tableData.length>0">（选中设备即为当前页设备）</span></view> 
			<view v-if="tableData.length>0" class="isAllow tips">注：设备编码为红色文字的代表当前设备不可用</view>
		</view>
		<view class="table" v-if="tableData.length>0">
			<view class="tr">
				<view class="th">
					<checkbox value="0" style="transform:scale(.85)" :checked="isCheckedAll" @click="checkAll" />
				</view>
				<view class="th width-text"></view>
				<view class="th"></view>
				<view class="th width-text">操作</view>
			</view>
			<view class="tr" v-for="(item,index) in tableData" :key="index">
				<view class="td indexs">
					<checkbox :value="index+1" style="transform:scale(.85)" :checked="item.checked"
						@click="checkboxClick(index)" />
				</view>
				
				<view class="td width-text">
					<view>序号</view>
					<view class="bordert">编码</view>
					<view class="bordert">ID</view>
					<view class="bordert" v-if="item.resultCode">结果</view>
					<view class="bordert" v-if="item.resultCode&&item.resultCode !=200">描述</view>
				</view>
				<view class="td">
					<view>{{index+1}}</view>
					<view :class="[{'isAllow':!item.isAllowOperate},'bordert']">{{item.code?item.code:"无"}}</view>
					<view class="bordert">{{item.id}}</view>
					<view class="bordert" v-if="item.resultCode">
						{{item.resultCode == 200 ?'成功':'失败'}}
					</view>
					<view class="bordert" v-if="item.resultCode&&item.resultCode !=200">
						{{item.resultMessage}}
					</view>
				</view>
				<view class="td width-text indexs">
					<view class="iconfont icon-copy" v-if="item.code" @click="isCopy(item.code)"></view>
					<view>
						<uni-icons v-if="permission('applet:batchconnection:resend') && item.resultCode&&item.resultCode !=200" type="gear" size="24" color="#999999" @click="resendParam(index)">
						</uni-icons>
					</view>
				</view>
			</view>
		</view>
		
		<uni-pagination class="pagination" v-if="tableData.length>0" @change="changePage()" :pageSize="size" :current="page" :total="total"
			:show-icon="true" prev-text="前一页" next-text="后一页" />
			
		<view class="nodata" v-if="tableData.length == 0">
			<image class="empty_img" src="/static/images/empty.png" mode="widthFix"></image>
			<view>暂无数据</view>
		</view>
	</view>
</template>

<script>
	import {
		equipment,
		partType
	} from "@/api/my.js";
	import {
		removeNullUndefined,
		doCopy,
		unique
	} from "@/common/index.js";
	import {
		mapState,
	} from 'vuex';
	import {permission} from "@/common/permission.js";
	
	export default {
		data() {
			return {
				searchData: {
					codes: "",
				},
				tableData: [],
				// 每页数据量
				size: 30,
				// 当前页
				page: 1,
				total:0,
				
				operateForm: {
					deviceName: "",
					deviceSecret: "",
					password: "",
					port: "",
					productKey: "",
					url: "",
					username: "",
				},
				isCheckedAll: false, //全选
				equipIds: [], //所选设备ids
				resultData: {},
				nofoundList: [], //未找到code列表
				permission:permission,
			}
		},
		computed: {
			...mapState(['enums','equipTypeCode'])
		},
		
		watch: {
			enums: {
				async handler(val) {
					val.EQUIP_OPERATE_RESULT_STATUS.forEach(item => {
						this.resultData[item.code] = item.label;
					});
				},
				immediate: true,
			},

		},

		methods: {
			getDataList() {
				let param = {
					...this.searchData
				};
				if (param.codes) {
				    param.codes = param.codes.split("\n").filter(item=>item);
				}
				if(param.codes.length ==1){
					param.code = param.codes[0];
				    delete param.codes;
				}
				
				this.nofoundList = [];
				if (param.codes&& param.codes.length > 30) {
					this.$Toast.none('最多30个设备号～');
					return;
				}
				this.$Toast.loading('加载中~');
				equipment('/version/list', 'post', {
					...removeNullUndefined(Object.assign(param, {
						pageNum: this.page,
						pageSize: this.size,
						equipTypeCode: this.equipTypeCode
					}))
				}).then(res => {
					if (res.code == 200) {
						this.tableData = res.data;
						this.tableData.forEach(item => item.checked = false);
						this.isCheckedAll = false;
						
						this.total = +res.total;

						// 查找未搜索到的设备code
						if(param.codes){
							this.nofoundList = param.codes.filter(item => !this.tableData.some(ele => ele.code
							.toLowerCase() ==
							item.toLowerCase()));
						}else if(param.code){
							this.nofoundList = this.tableData.length ==0?[param.code]:[];
						}
					}
				}).finally(() => uni.hideLoading());
			},
			// 分页
			changePage(e) {
				this.page = e.current;
				this.getDataList();
			},

			// 搜索
			doSearch() {
				let param = {
					...this.searchData
				};
				
				if (param.codes) {
				    param.codes = param.codes.split("\n").filter(item=>item);
				}
				if (param.codes.length ==0) {
					this.$Toast.none('请输入柜号');
					return;
				}
				this.getDataList();
			},
			// 复制
			isCopy(item) {
				doCopy(item);
			},
			onPasswordInput(type){
				setTimeout(() => {
					this.operateForm[type] = this.operateForm[type].replace(/\s+/g, '');
					this.operateForm[type] = this.operateForm[type].replace(/[\u4E00-\u9FA5]/g,'')
				}, 10)
			},

			isSetting() {
				this.equipIds = this.tableData.filter(item => item.checked).map(p => {
					return p.id
				});
				let onlineList = this.tableData.filter(item => item.checked && item.isAllowOperate); //可操作设备
				
				if (this.tableData.length == 0) {
					this.$Toast.none('暂无设备，请先搜索~');
					return;
				}
				else if (this.equipIds.length == 0) {
					this.$Toast.none('请选择需要设置的设备');
					return;
				} 
				else if (this.equipIds.length > 0 && onlineList.length == 0) {
					this.$Toast.none('设备离线/禁用不可操作！');
					return;
				}
				else if (!this.operateForm.url) {
					this.$Toast.none('请输入服务地址');
					return;
				} else if (!this.operateForm.port) {
					this.$Toast.none('请输入端口');
					return;
				} else if (!this.operateForm.username) {
					this.$Toast.none('请输入用户名');
					return;
				} else if (!this.operateForm.password) {
					this.$Toast.none('请输入密码');
					return;
				} else if (!this.operateForm.productKey) {
					this.$Toast.none('请输入产品密钥');
					return;
				} else if (!this.operateForm.deviceName) {
					this.$Toast.none('请输入设备名称');
					return;
				} else if (!this.operateForm.deviceSecret) {
					this.$Toast.none('请输入设备密钥');
					return;
				}
				let that = this;
				let msg = '';
				if (onlineList.length < this.equipIds.length) { //选中设备包含离线
					msg = "离线/禁用设备不可操作，已自动过滤！"
				}
				uni.showModal({
					title: '提示',
					content: this.equipIds.length > 1 ? `${msg}确定要批量设置吗？` : `${msg}确定要设置吗？`,
					success(res) {
						if (res.confirm) {
							that.dividerGroup();
						}
					}
				})
			},

			dividerGroup() {
				let that = this;
				let arr = this.tableData.filter(item => item.checked && item.isAllowOperate).map(p=>{
					return p.id
				}); //过滤选中且可操作项
				
				let arrr = [];
				let result = arr.reduce(function(pre, item, index, arr) {
					let begin = index * 5;
					let end = begin + 5;
					let res = arr.slice(begin, end);
					if (res.length != 0) {
						arrr[index] = res;
					}
					return arrr;
				}, []);

				this.$Toast.loading('设置中~');
				// 5个一组,每次下发5个
				(function(arr) {
					let i = 0,
						length = result.length;
					(function a() {
						let timer = setTimeout(function() {
							let lng = i == length - 1 ? true : false;
							that.doSetting(result[i++], lng);
							i < length && a();
						}, 300);
					}())
				}(result));
			},
			// 设置
			doSetting(arr, isLast) {
				// isLast 是否最后一组
				for (let i = 0; i < arr.length; i++) {
					equipment(`/control/op/connectionparam/${arr[i]}`,
							'post', this.operateForm).then(res => {
							let inx = this.tableData.findIndex(item => item.id == arr[i]);
							this.$set(this.tableData[inx], 'resultCode', res.code);
							this.$set(this.tableData[inx], 'resultMessage', res.message);
						}).finally(() => {
							if (isLast && i == arr.length - 1) {
								this.$Toast.none('操作完成~');
							}
						})
						.catch(err => {
							let inx = this.tableData.findIndex(item => item.id == arr[i]);
							this.$set(this.tableData[inx], 'resultCode', err.code);
							this.$set(this.tableData[inx], 'resultMessage', err.message);
						});
				}
			},
			//限制输入特殊字符
			keyUp(e) {
				let str = e.target.value.replace(
					/[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
					""
				);
				e.target.value = str;
				this.searchData.codes = str;
			},
			// 只能输入汉字、英文、数字
			keyInput(e) {
				let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
				e.target.value = str;
				this.searchData.codes = str;
			},
			keyBlur() {
				let codes = JSON.parse(JSON.stringify(this.searchData.codes));
				codes = unique(codes.split("\n"));
				this.searchData.codes = codes.join('\n');
			},
			checkboxClick(e) {
				this.tableData[e].checked = !this.tableData[e].checked;

				let checkList = this.tableData.filter(item => item.checked);
				if (checkList.length == this.tableData.length) {
					this.isCheckedAll = true;
				} else {
					this.isCheckedAll = false;
				}
			},
			checkAll() {
				this.isCheckedAll = !this.isCheckedAll;
				if (this.isCheckedAll) {
					this.tableData.forEach(item => item.checked = true);
				} else {
					this.tableData.forEach(item => item.checked = false);
				}
			},
			// 参数重设
			resendParam(e) {
				this.tableData.forEach(item => item.checked = false);
				this.checkboxClick(e);
				this.isSetting();
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "@/static/css/common";
	@import "@/static/iconfont.css";

	.content {
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}

	// .operate-group {
	// 	height: 100%;
	// 	@include flexLayout(center, space-between);
	// 	flex-direction: column;
	// }

	.search_btns {
		text-align: right;
		margin: 10rpx 0 0;

		button {
			background-color: #51b7b9;
		}
	}

	.textareas {
		box-sizing: border-box;
		width: 100%;
		border: 2rpx solid #E5E5E5;
		padding: 10rpx;
		word-break: break-all;
		word-wrap: break-word;
	}

	.table-title {
		margin: 0 0 10rpx;
		color: #333333;
		font-size: 32rpx;
		font-weight: 500;
	}

	.tab {
		/deep/ .segmented-control__item {
			justify-content: flex-start;
		}

		/deep/ .segmented-control__item--text {
			border-bottom: 2px solid #51b7b9;
			color: #51b7b9 !important;
		}
	}

	.param-content {
		padding: 0 20rpx;

		.param-one {
			line-height: 72rpx;
			@include flexLayout(center, flex-start);
			border-bottom: 2rpx solid #E5E5E5;
			font-size: 28rpx;
			color: #333333;

			text {
				width: 160rpx;
			}
		}
	}

	.table {
		width: 100%;
		border-radius: 8rpx;
		display: table;
		border: 2rpx solid #dfdfdf;
		border-collapse: collapse;
		color: #333333;
		font-size: 28rpx;
		margin-bottom: 120rpx;
	}

	.th {
		text-align: center;
		padding: 10rpx 0;
		font-weight: bolder;
		display: table-cell;
		border: 2rpx solid #dfdfdf
	}

	.td {
		text-align: center;
		background: #FFFFFF;
		padding: 10rpx 0;
		display: table-cell;
		border: 2rpx solid #dfdfdf;
		view{
			min-height: 50rpx;
		}
	}

	.tr {
		display: table-row;
		border: 2rpx solid #dfdfdf;
	}
	.indexs {
		vertical-align: middle;
	}

	.width-text {
		width: 76rpx;
	}

	.versions {
		padding: 0 10rpx;
		text-align: left;
	}

	.bordert {
		border-top: 2rpx solid #dfdfdf;
		padding-top: 10rpx;
		margin-top: 10rpx;
	}

	.nodata {
		margin: 10% 0 5%;
	}

	/deep/ .uni-list-item__container {
		padding: 16rpx 20rpx;
	}
	.isAllow {
		color: red;
	}
	.tips{
		font-size: 28rpx;
		margin-top: 10rpx;
	}
	.pagination {
		width: 100%;
		position: fixed;
		bottom: 20rpx;
		left: 0;
		background: #FFFFFF;
		padding: 20rpx 0;
	}
	
	.icon-copy {
		font-size: 36rpx;
		color: #666666;
	}
</style>
